<template>
  <el-form ref="adGroupForm" :model="adGroupForm" :rules="adGroupFormRules">
      <el-form-item label="投放地区">
        <div style="margin-left: 10px;margin-right: 10px;">
          <el-switch
            v-model="adGroupForm.locationEnable"
            :active-color="activeColor"
            :inactive-color="inactiveColor"
            :active-value="1"
            :inactive-value="0"
            @change="handleChangeLocation"
          >
          </el-switch>
        </div>
      </el-form-item>
      <el-form-item prop="locationIds">
        <el-select v-model="adGroupForm.locationIds" placeholder="请选择" size="mini"
                   multiple
                   filterable
                   :disabled="adGroupForm.locationEnable === 0"
        >
          <el-option
            v-for="item in locationList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="语言">
        <div style="margin-left: 10px;margin-right: 10px;">
          <el-switch
            v-model="adGroupForm.languageEnable"
            :active-color="activeColor"
            :inactive-color="inactiveColor"
            :active-value="1"
            :inactive-value="0"
            @change="handleChangeLanguage"
          >
          </el-switch>
        </div>
      </el-form-item>
      <el-form-item>
        <el-select v-model="adGroupForm.languages" placeholder="不限" size="mini"
                   multiple
                   filterable
                   clearable
                   :disabled="adGroupForm.languageEnable === 0"
        >
          <el-option v-for="item in languagesList"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="性别">
        <div style="margin-left: 10px;margin-right: 10px;">
          <el-switch
            v-model="adGroupForm.genderEnable"
            :active-color="activeColor"
            :inactive-color="inactiveColor"
            :active-value="1"
            :inactive-value="0"
            @change="handleChangeGender"
          >
          </el-switch>
        </div>
      </el-form-item>
      <el-form-item>
        <el-radio-group v-model="adGroupForm.gender" size="mini" :disabled="adGroupForm.genderEnable === 0">
          <el-radio-button v-for="item in genderList" :key="item.value" :label="item.value">{{
            item.label
            }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="年龄">
        <div style="margin-left: 10px;margin-right: 10px;">
          <el-switch
            v-model="adGroupForm.ageEnable"
            :active-color="activeColor"
            :inactive-color="inactiveColor"
            :active-value="1"
            :inactive-value="0"
            @change="handleChangeAge"
          >
          </el-switch>
        </div>
      </el-form-item>
      <el-form-item>
        <cs-radio-checkbox v-model="adGroupForm.age" :props="ageGroupsList" :disabled.sync="adGroupForm.ageEnable === 0"
        ></cs-radio-checkbox>
      </el-form-item>
  </el-form>
</template>
<script>
  import {getLanguagesList} from "@/util/beetles"
  import {
    getActionCategories,
    getInterestByKeyword,
    getLocationTreeByTargeting,
    getTiktokInterestTree
  } from "@/api/campaign-management/campaign-management";
  import CsRadioCheckbox from "@/components/CsRadioCheckbox/CsRadioCheckbox";
  import _ from "lodash";

  export default{
    name:"AdGroupTargetingForm",
    components:{
      CsRadioCheckbox
    },
    props:{
      locations: {
        type: Array
      },
    },
    computed:{
      locationList:{
        get(){
          return this.locations
        }
      }
    },
    created(){
      // this.getLocationTree()
      this.languagesList = getLanguagesList()
      // this.getTiktokInterestTree()
      // this.getVideoRelatedTree()
      // this.getCreatorRelatedTree()
    },
    data(){
       var validateLocations = (rule, value, callback) => {
        if(this.adGroupForm.locationEnable === 1){
          if(value.length === 0){
            callback(new Error('请选择至少一个投放地区'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return{
        adGroupFormRules: {
          locationIds: [{validator: validateLocations, trigger: "change"}]
        },
        activeColor: "#13ce66",
        inactiveColor: "#ccc",
        checkboxNetworkState: [], // 废弃
        tempValue: '',
        creatorRelatedTree: [],
        videoRelatedTree: [],
        queryInterestsLoading: false,
        interestBtnLoading: false,
        adGroupForm: {
          locationPlacements: {},
          locationLabels: {},
          languageEnable: 0,
          ageEnable: 0,
          genderEnable: 0,
          locationEnable: 0,
          // 优化目标
          optimizationGoal: 'INSTALL',
          // 优化事件
          optimizationEvent: '',
          // 出价费用
          bidPrice: '',
          conversionBidPrice: '',
          // 次日留存率
          dailyRetentionRatio: '',
          // 选择受众
          audienceIds: [],
          // 排除受众
          excludedAudienceIds: [],
          // 家庭收入
          householdIncome: [],
          // 兴趣
          interestCategoryIds: [],
          // 视频互动
          videoRelatedCategoryIds: [],
          // 作者互动
          creatorRelatedCategoryIds: [],
          // 话题互动 (temp)
          // topicInteraction: '',
          // 设备定向扩量
          expansionEnabled: 0,
          // 国家地区 数组
          locationIds: [],
          // 语言
          languages: [],
          // 性别
          gender: 'GENDER_UNLIMITED',
          // 年龄
          age: [],
          // 竞价策略
          bidType: 'BID_TYPE_NO_BID',
          // 投放速度
          pacing: 'PACING_MODE_SMOOTH',
          // 设置广告花费回报(ROAS)下限值
          isSetROAS: false,
          //深度事件出价类型
          deepBidType: '',
          // 用于价值优化的ROAS目标值
          roasBid: '',
          // 定向扩量
          expansionTypes: [],
          // 定向扩量阻止开关
          expansionswitch: false,
          // 视频相关行为
          videoUserActions: {
            VIDEO_RELATED: [],
            CREATOR_RELATED: []
          },
          // 选择n天内发生的行为
          actionPeriod: '',
          creatorRelatedCategory: [],
          videoRelatedCategory: [],
          interestCategory: [],
          interestsByKeyword: [],
          interestsByKeywordIds: [],
          excludedAudience: '',
          audience: '',
          // 推广目标
          objectiveType: 'APP_INSTALL',
        },
        // 年龄
        ageGroupsList: [
          {
            label: '13-17岁',
            value: 'AGE_13_17'
          }, {
            label: '18-24岁',
            value: 'AGE_18_24'
          }, {
            label: '25-34岁',
            value: 'AGE_25_34'
          }, {
            label: '35-44岁',
            value: 'AGE_35_44'
          }, {
            label: '45-54岁',
            value: 'AGE_45_54'
          }, {
            label: '55+',
            value: 'AGE_55_100'
          },],
        //语言
        languagesList: [],
        // 性别
        genderList: [
          {
            label: '不限',
            value: 'GENDER_UNLIMITED'
          }, {
            label: '男性',
            value: 'GENDER_MALE'
          }, {
            label: '女性',
            value: 'GENDER_FEMALE'
          }
        ],
        // 家庭收入
        householdIncomeList: [
          {value: "TOP5", label: "家庭收入群体的前5%"},
          {value: "TOP10", label: "家庭收入群体的前10%"},
          {value: "TOP10_25", label: "家庭收入群体的前10-25%"},
          {value: "TOP25_50", label: "家庭收入群体的前25-50%"}
          ],
        // 兴趣列表
        tiktokInterestTree: [],
        tiktokInterestList: [],
        // 其他兴趣
        otherInterestList: [],
        networkStateList: [
          {
            label: '不限',
            value: '不限'
          }, {
            label: 'WIFI',
            value: 'WIFI'
          }, {
            label: '2G',
            value: '2G'
          }, {
            label: '3G',
            value: '3G'
          }, {
            label: '4G',
            value: '4G'
          }, {
            label: '5G',
            value: '5G'
          },
        ],
      }
    },
    methods:{
      handleChangeLocation(val){
        if(val === 0){
          this.adGroupForm.locationIds = []
        }
      },
      handleChangeAge(val){
        this.adGroupForm.age = []
      },
      handleChangeGender(val){
        this.adGroupForm.gender = 'GENDER_UNLIMITED'
      },
      handleChangeLanguage(val){
        this.adGroupForm.languages = []
      },
      // 获取兴趣列表
      async getTiktokInterestTree(refresh) {
        this.interestBtnLoading = true
        const {data: res} = await getTiktokInterestTree({
          refresh: refresh || false
        }).finally(() => {
          this.interestBtnLoading = false
        })
        // console.log(res)
        this.tiktokInterestTree = res.data
        this.tiktokInterestList = []
        this.transformList(res.data, this.tiktokInterestList)
      },
      // 兴趣选择
      handleInterestNodeClick(data, self, child) {
        this.adGroupForm.interestCategoryIds = this.$refs.tiktokInterestTreeC.getCheckedNodes(true).map(item => item.value)
      },
      async queryInterestsByKeyword(queryString) {
        this.queryInterestsLoading = true
        const {data: res} = await getInterestByKeyword(this.currentAccountId, queryString).finally(() => {
          this.queryInterestsLoading = false
        })
        this.otherInterestList = res.data

      },
      handleChangeOtherInterest(val) {
        const prop = this.otherInterestList.filter(item => val.includes(item.id))
        this.adGroupForm.interestsByKeyword.push(...prop)
        this.adGroupForm.interestsByKeyword = _.uniqWith(this.adGroupForm.interestsByKeyword, _.isEqual)
      },
      handleChangeVideoRelated() {
        if (this.adGroupForm.videoUserAction.VIDEO_RELATED.length === 0 && this.adGroupForm.videoRelatedCategory.length === 0) {
          this.$refs.adGroupForm.clearValidate('videoRelatedCategoryIds')
          this.$refs.adGroupForm.clearValidate('videoUserAction.VIDEO_RELATED')
        }
      },
      // 行为视频互动点击
      handleVideoNodeClick() {
        if (this.adGroupForm.videoUserActions.VIDEO_RELATED.length === 0 && this.adGroupForm.videoRelatedCategory.length === 0) {
          this.$refs.adGroupForm.clearValidate('videoRelatedCategoryIds')
          this.$refs.adGroupForm.clearValidate('videoUserActions.VIDEO_RELATED')
        }
        this.adGroupForm.videoRelatedCategoryIds = this.$refs.videoRelatedTreeC.getCheckedNodes(true).map(item => item.value)
      },
      // 行为 作者
      handleCreatorNodeClick() {
        this.adGroupForm.creatorRelatedCategoryIds = this.$refs.creatorRelatedTreeC.getCheckedNodes(true).map(item => item.value)
      },
      async getLocationTree() {
        const {data: res} = await getLocationTreeByTargeting()
        this.locationList = res.data
        this.buildLocationPlacement()
      },
      buildLocationPlacement(){
        this.locationList.forEach(location => {
          this.adGroupForm.locationPlacements[location.value] = location.placements
          this.adGroupForm.locationLabels[location.value] = location.label
        })
      },
      // 添加行为:创作者互动
      async getVideoRelatedTree(refresh) {
        const {data: res} = await getActionCategories({
          refresh: refresh || false,
          type: 'VIDEO_RELATED'
        })
        this.videoRelatedTree = res.data
        this.videoRelatedList = []
        this.transformList(res.data, this.videoRelatedList)
      },
      // 添加行为:视频互动
      async getCreatorRelatedTree(refresh) {
        const {data: res} = await getActionCategories({
          refresh: refresh || false,
          type: 'CREATOR_RELATED'
        })
        this.creatorRelatedTree = res.data
        this.creatorRelatedList = []
        this.transformList(res.data, this.creatorRelatedList)
      },
      // 把属性结构结果转换成数组
      transformList(tree, res) {
        tree.forEach(item => {
          if (item.hasOwnProperty('children')) {
            this.transformList(item.children, res)
          } else {
            res.push({
              label: item.label,
              value: item.value
            })
          }
        })
      },
    }
  }
</script>
